package com.freecloud.whispered.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.freecloud.framework.constant.Constant;
import com.freecloud.framework.exceptions.RRException;
import com.freecloud.framework.service.AbstractBaseService;
import com.freecloud.whispered.auth.entity.SysUserEntity;
import com.freecloud.whispered.auth.repository.SysUserDao;
import com.freecloud.whispered.auth.service.SysRoleService;
import com.freecloud.whispered.auth.service.SysUserRoleService;
import com.freecloud.whispered.auth.service.SysUserService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


/**
 * 系统用户
 * 
 * @author maomao
 * @email 138383877@qq.com
 */
@Service("sysUserService")
public class SysUserServiceImpl  extends AbstractBaseService<SysUserEntity,Long, SysUserDao> implements SysUserService {
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;

	@Override
	public List<String> queryAllPerms(Long userId) {
		return sysUserDao.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return sysUserDao.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return sysUserDao.queryByUsername(username);
	}

	@Override
	@Transactional
	public SysUserEntity save(SysUserEntity user) {
		user.setCreateTime(new Date());
		//sha256加密
		user.setPassword(new Sha256Hash(user.getPassword()).toHex());
		sysUserDao.save(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
		return user;
	}

	@Override
	@Transactional
	public SysUserEntity update(SysUserEntity user) {
		if(StrUtil.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword()).toHex());
		}
		sysUserDao.save(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
		return user;
	}

	@Override
	public int updatePassword(Long userId, String password, String newPassword) {
		return sysUserDao.updatePassword(userId,password,newPassword);
	}
	
	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user){
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(user.getCreateUserId() == Constant.SUPER_ADMIN){
			return ;
		}
		
		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());
		
		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new RRException("新增用户所选角色，不是本人创建");
		}
	}

	@Override
	public SysUserEntity queryUserById(Long userid) {
		return this.queryObject(userid);
	}
}
